package com.slipper.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class MD5 {
    private static final Logger logger = LoggerFactory.getLogger(MD5.class);

    /**
     * 将源字符串使用MD5加密为字节数组
     */
    public static byte[] encode2bytes(String source) {
        byte[] result = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(source.getBytes(StandardCharsets.UTF_8));
            result = md.digest();
        } catch (Exception e) {
            logger.error("", e);
        }
        return result;
    }

    /**
     * 将源字符串使用MD5加密为32位16进制数
     */
    public static String encode2hex(String source) {
        byte[] data = encode2bytes(source);
        StringBuilder hexString = new StringBuilder();
        for (byte datum : data) {
            String hex = Integer.toHexString(0xff & datum);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static String encode(String s) {
        if (s == null || s.isEmpty()) {
            return null;
        }
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (java.security.NoSuchAlgorithmException ex) {
            // 断言失败：JDK 带有 MD5 算法实现
            throw new AssertionError(ex);
        }
        byte[] res = md.digest(s.getBytes(StandardCharsets.UTF_8));
        return MD5.dumpBytes(res);
    }

    private static String dumpBytes(byte[] bytes) {
        int size = bytes.length;
        StringBuilder sb = new StringBuilder(size * 2);
        String s;
        for (byte aByte : bytes) {
            s = Integer.toHexString(aByte);
            if (s.length() == 8) { // -128 <= bytes[i] < 0
                sb.append(s.substring(6));
            } else if (s.length() == 2) { // 16 <= bytes[i] < 128
                sb.append(s);
            } else {
                sb.append("0").append(s); // 0 <= bytes[i] < 16
            }
        }
        return sb.toString();
    }

    public static String encodeOld(String s) {
        String encryptStr = s + "202cb962ac59075b964b07152d234b70";
        String first = encryptStr.substring(0, 32);
        String last = encryptStr.substring(32);
        return encode(first) + encode(last);
    }
    
    public static void main(String[] args) {
        System.out.println(encode("12345"));
    }
}
